*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*	This program estimates OLS VAM for MSE simulations.
*	----------------------------------------------------------------------------
	args sample sch_res ptype bw
	tokenize `sample', parse("_")
	local years "`5'`6'`7'`8'"

	// pick VAMs to estimate
	local vams unc conv risk rcvam conv_3yrlag

*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

*	load
	use "${builddata}${city}_analysisfile`sample'`sch_res'`bw'", clear

*	get schools
	preserve

		if "${city}" == "NYC" {
			drop enr_4555
			drop enr_2337
			drop enr_2583
			drop enr_3459
			drop enr_3552
			drop enr_6334
			drop enr_6365
			drop enr_6403
			drop enr_6524
			drop enr_6564
			drop enr_6388
		}
		if "${city}" == "NYCms" {
			drop enr_6593
			drop enr_3349
		}

		_rmcoll enr_???? if lottery_`ptype'_sample, forcedrop nocons
			local D = r(varlist)

		gen tag = 0
		foreach var of varlist `D'{
			local sch=substr("`var'",-4,.)
			replace tag = 1 if sch == `sch'
		}
		keep if tag

		keep sch lottery_`ptype'_sch omitted
		duplicates drop

		//lotteries first
		gsort omitted -lottery_`ptype'_sch sch
		gen newnum = _n

		//count schools
		local J=_N
		count if lottery_`ptype'_sch & !omitted
		local L=r(N)

		//store ordering in locals
		forval i=1/`J'{
			qui sum sch if newnum == `i'
			local oldnum_`i' = r(mean)
			di in red "`oldnum_`i''"
		}

	restore

	local D
	local enrvar enr
	forval k=1/1{
		forval i=1/`J'{
			gen `enrvar'_`oldnum_`i''_`k' = `enrvar'_`oldnum_`i''
			local D `D' `enrvar'_`oldnum_`i''_`k'
		}
	}

*	set variables
	ivset, ptype(`ptype')
		local p = r(P)

*** estimate OLS VAMs

	foreach vam in `vams' {
		if "`vam'" == "unc" 	qui _regress math `D' i.year, nocons
		if "`vam'" == "conv" 	qui _regress math `D' $iv_controls, nocons
		if "`vam'" == "risk" 	qui _regress math `D' i.year `p', nocons
		if "`vam'" == "rcvam" 	qui _regress math `D' $iv_controls `p', nocons
		if "`vam'" == "conv_3yrlag" {
			u "${builddata}${city}_analysisfile`sample'`sch_res'`bw'_older_bl", clear
			local D
			local enrvar enr
			forval k=1/1{
				forval i=1/`J'{
					gen `enrvar'_`oldnum_`i''_`k' = `enrvar'_`oldnum_`i''
					local D `D' `enrvar'_`oldnum_`i''_`k'
				}
			}
			qui _regress math `D' $iv_controls, nocons
		}
		mat b = e(b)
		mat b = b[1..1,1..`J']
		mat V = e(V)
		mat V = V[1..`J',1..`J']
		mat T = I(`J') - J(`J',`J',1/`J')
		mat b = b*T
		preserve
			clear
			svmat V
			export delimited using "${builddata}${city}_V_`vam'.csv", novarnames replace
			clear
			svmat b
			export delimited using "${builddata}${city}_b_`vam'.csv", novarnames replace
		restore
	}
